import wx
from webbrowser import open as web_open
import urllib2
import feedparser

class GmailChecker(wx.MiniFrame):
    def __init__(self):
        displaySize = wx.GetDisplaySize()
        wx.MiniFrame.__init__(self, None, -1, "Gmail",
                              pos=(displaySize[0]-610, displaySize[1]-230),
                              size=(610,200), style=wx.DEFAULT_FRAME_STYLE
                                                    |wx.STAY_ON_TOP)
        self.tbicon = wx.TaskBarIcon()
        self.iconNoMail = wx.Icon('no_mail.png', wx.BITMAP_TYPE_PNG)
        self.iconMail = wx.Icon('mail.png', wx.BITMAP_TYPE_PNG)
        self.tbicon.SetIcon(self.iconNoMail, '')
        
        wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarLeftDClick)
        wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarRightClick)
        self.hasMail = False
        
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.list = wx.ListCtrl(self, -1, style=wx.LC_REPORT
                                               |wx.BORDER_NONE
                                               |wx.LC_HRULES,
                                                size=self.GetSize())
        self.list.InsertColumn(0, "From")
        self.list.InsertColumn(1, "Subject")
        self.list.InsertColumn(2, "Summary")
        self.list.SetColumnWidth(0, 50)
        self.list.SetColumnWidth(1, 100)
        self.list.SetColumnWidth(2, 450)
        self.list.Bind(wx.EVT_LEFT_DCLICK, self.onLaunchGmail)
        sizer.Add(self.list, 0,  flag=wx.EXPAND)
        self.Bind(wx.EVT_CLOSE, self.OnTaskBarLeftDClick)
        self.SetSizer(sizer)
        
        with open("config.ini") as f:
            configlines = [line.split("=") for line in f.readlines()]
            for line in configlines:
                if line[0].strip()=="username":self.userName = line[1].strip()
                elif line[0].strip()=="password":self.password = line[1].strip()
                elif line[0].strip()=="check_interval":self.checkInterval = int(line[1].strip())
        
        ID_TIMER = wx.NewId()
        self.timerCheck = wx.Timer(self, ID_TIMER)
        self.Bind(wx.EVT_TIMER, self.checkMail, self.timerCheck)
        self.timerCheck.Start(1000*60*self.checkInterval) #every 3 minutes
        
        self.GMAIL_URL = "https://mail.google.com/gmail/feed/atom"
        
        passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
        passman.add_password(None, "https://mail.google.com",
                             self.userName, self.password)
        authhandler = urllib2.HTTPBasicAuthHandler(passman)
        self.opener = urllib2.build_opener(authhandler)    
        #urllib2.install_opener(self.opener) #don't need this, or use urlopen
        self.checkMail(None)
        
        self.Show(True)
        
    def OnTaskBarLeftDClick(self, evt):
        self.Show(not self.IsShown())
        
    def OnTaskBarRightClick(self, evt):
        self.Show(True)
        self.Destroy()
        
    def onLaunchGmail(self, evt):
        web_open("https://mail.google.com")
        
    def checkMail(self, evt):
        self.list.DeleteAllItems()
        try:
            f = self.opener.open(self.GMAIL_URL)
        except:
            if evt:evt.Skip()
            self.SetTitle("Gmail - Cannot retrieve mails, check your config.ini file and your internet connection.")
            return
        
        #feed reading
        feed = f.read()
        atom = feedparser.parse(feed)
        if len(atom.entries)>0:
            self.SetTitle("Gmail - (%d) new mail%s"%(len(atom.entries),
                                            "s" if len(atom.entries)>1 else ""))
            for mail in atom.entries:
                index = self.list.InsertStringItem(0, mail.author)
                self.list.SetStringItem(index, 1, mail.title)
                self.list.SetStringItem(index, 2, unicode(mail.summary_detail.value))
            self.tbicon.SetIcon(self.iconMail, '')
        else:
            self.SetTitle("Gmail - (0) new mail")
            self.tbicon.SetIcon(self.iconNoMail, '')


if __name__=="__main__":
    app = wx.App()
    app.RestoreStdio()
    GmailChecker()
    app.MainLoop()